package controller

import (
	"github.com/gin-gonic/gin"
	"web/app"
	"web/app/enum"
	"web/conf"
	"web/util"
)

type c_admin struct {

}

func (a *c_admin) login(c *gin.Context) {
	user := c.PostForm("user")
	pwd := c.PostForm("pwd")
	if user != conf.Conf_Get("login.user") || pwd != conf.Conf_Get("login.pwd") {
		app.Response(c, 400, "账号或密码错误")
		return
	}

	time := util.GetTime()
	err, token := app.SignToken(&app.AUTO{Time_upData: time, Power: enum.Auto_admin})
	if err != nil {
		app.Response(c, 400, err.Error())
		return
	}

	conf.Conf_Set("login.time", time)
	conf.Conf_Save()
	app.Response_data(c, 200, "登录成功", token)
}

func (a *c_admin) newPwd(c *gin.Context) {
	oldPwd := c.PostForm("oldPwd")
	newPwd := c.PostForm("newPwd")
	if oldPwd != conf.Conf_Get("login.pwd") {
		app.Response(c, 400, "原密码错误")
		return
	}

	conf.Conf_Set("login.pwd", newPwd)
	conf.Conf_Set("login.time", util.GetTime())
	conf.Conf_Save()
	app.Response(c, 200, "密码已修改,请重新登录")
}

func (a *c_admin) out(c *gin.Context) {
	conf.Conf_Set("login.time", 0)
	conf.Conf_Save()
	app.Response(c, 200, "账号已退出")
}

type i_admin interface {
	login(c *gin.Context)
	newPwd(c *gin.Context)
	out(c *gin.Context)
}
